package tt.dz.appserver.service.business.imp;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.avro.AvroRemoteException;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tt.dz.appserver.dao.ext.UserInfoDao;
import tt.dz.appserver.entity.model.ResultMappingEntity;
import tt.dz.appserver.entity.model.user.UserInfo;
import tt.dz.appserver.entity.vo.UsingNum;
import tt.dz.appserver.entity.vo.charger.ChargerDetailVo;
import tt.dz.appserver.entity.vo.charger.DeviceTypeInfoVo;
import tt.dz.appserver.entity.vo.charger.PlugNoDetailVo;
import tt.dz.appserver.entity.vo.charger.RateVo;
import tt.dz.appserver.entity.vo.user.UserDetailVo;
import tt.dz.appserver.service.avro.client.oms.dzttOmsServiceProtocol;
import tt.dz.appserver.service.business.ChargerService;
import tt.dz.appserver.service.business.UserInfoService;
import tt.dz.appserver.util.CodeUtils;
import tt.dz.appserver.util.Constants;
import tt.dz.appserver.util.Result;
import tt.dz.appserver.util.dzcode.OmsCode;
import tt.dz.appserver.util.enums.Response;
import tt.dz.appserver.util.json.JsonUtils;

/**
 * 电桩业务实现类
 * 
 * @author Administrator
 *
 */
public class ChargerServiceImpl implements ChargerService {

	/** 日志 */
	private static final Logger LOG = Logger.getLogger("[电桩业务接口]:");

	/** oms服务接口 */
	@Resource(name = "omsMessageProtocolRequestor")
	private dzttOmsServiceProtocol omsService;

	/** 用户业务 */
	@Resource
	private UserInfoService userInfoService;

	/** 用户数据操作 */
	@Resource
	private UserInfoDao userInfoDao;

	@Override
	public JSONObject getFreeChargerNum(String stationId) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();

		String resultJsonString = omsService.getFreeChargerByStationId(stationId).toString();

		LOG.info("获取【" + stationId + "】 此电站自由桩,OMS返回详细:" + resultJsonString);
		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		// 获取操作结果
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);

		// 操作成功
		if (OmsCode.SUCCESS.equals(code)) {

			// 空闲桩的数量
			JSONObject freeNums = omsResultObject.getJSONObject("pojo");

			String freeDirectNum = freeNums.getString("free_Chargers_count_direct");
			String freeAlternateNum = freeNums.getString("free_Chargers_count_alter");

			// 交流和直流数量
			resultJsonObject.put("freeDirectNum", freeDirectNum);
			resultJsonObject.put("freeAlternateNum", freeAlternateNum);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			Response response = CodeUtils.getCodeByOMSServerCode(code);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject getChargerListByStationId(String stationId) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();

		String resultJsonString = omsService.getChargerListByStationId(stationId).toString();

		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		// 获取操作结果
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);

		LOG.info("获取【" + stationId + "】 此电站的电桩列表,OMS接口返回代码" + code);

		// 操作成功
		if (OmsCode.SUCCESS.equals(code)) {

			// 获取电桩列表
			JSONArray chargersList = omsResultObject.getJSONArray("list");
			// 需要返回的列表
			List<ChargerDetailVo> resultChargersList = new ArrayList<ChargerDetailVo>();
			int chargersCount = chargersList.size();
			for (int i = 0; i < chargersCount; i++) {

				JSONObject charger = chargersList.getJSONObject(i);

				// 封装字段
				ChargerDetailVo chargerDetailVo = JsonUtils.JsonToObjectOfClass(charger, ChargerDetailVo.class);
				
				//设备类型
				JSONObject deviceTypeJson = charger.getJSONObject("deviceType");
				if(deviceTypeJson!=null){
					DeviceTypeInfoVo deviceTypeVo = JsonUtils.JsonToObjectOfClass(deviceTypeJson, DeviceTypeInfoVo.class);
					chargerDetailVo.setDeviceType(deviceTypeVo);
				}
				
				// 获取桩的枪头列表
				String plugNoResultJsonString = omsService.getChargerPortsByChargerId(chargerDetailVo.getChargerId())
						.toString();

				// json转换
				JSONObject plugNoResultObject = JSONObject.parseObject(plugNoResultJsonString);
				List<PlugNoDetailVo> detailVos = new ArrayList<>();
				// 获取操作结果
				String plugNocode = omsResultObject.getString(Constants.OmsServerResultField.CODE);

				LOG.info("获取 【" + chargerDetailVo.getChargerId() + "】 桩充电插头列表接口,OMS返回代码:" + plugNocode);

				if (OmsCode.SUCCESS.equals(plugNocode)) {
					JSONArray plugNoJsonArray = plugNoResultObject.getJSONArray("list");
					for (int j = 0; j < plugNoJsonArray.size(); j++) {

						// 获取插头json对象
						JSONObject plugNoJson = plugNoJsonArray.getJSONObject(j);
						String portNo = plugNoJson.getString("port_no");
						String chargeStatus = plugNoJson.getString("charge_status");

						// 封装插头详细
						PlugNoDetailVo plugNoDetailVo = new PlugNoDetailVo();
						plugNoDetailVo.setPortNo(portNo);
						plugNoDetailVo.setChargeStatus(chargeStatus);
						detailVos.add(plugNoDetailVo);
					}
				}
				chargerDetailVo.setPlugNoList(detailVos);

				resultChargersList.add(chargerDetailVo);

			}

			resultJsonObject.put("chargerList", resultChargersList);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			Response response = CodeUtils.getCodeByOMSServerCode(code);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject getChargerDetailByChargerId(String chargerId) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();

		String resultJsonString = omsService.getChargerDetailByChargerId(chargerId).toString();

		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		// 获取操作结果
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);

		LOG.info("OMS获取 【" + chargerId + "】 电桩详细,接口返回代码:" + code);

		// 操作成功
		if (OmsCode.SUCCESS.equals(code)) {

			JSONObject charger = omsResultObject.getJSONObject("pojo");

			// 封装字段
			ChargerDetailVo chargerDetailVo = JsonUtils.JsonToObjectOfClass(charger, ChargerDetailVo.class);

			resultJsonObject.put("chargerDetailVo", chargerDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			Response response = CodeUtils.getCodeByOMSServerCode(code);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject getChargerDetailByQrCode(String qrCode) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();

		String resultJsonString = omsService.getChargerDetailByQrCode(qrCode).toString();

		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		// 获取操作结果
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);

		LOG.info("获取二维码为【" + qrCode + "】 电桩详细接口,OMS返回代码为:" + code);

		// 操作成功
		if (OmsCode.SUCCESS.equals(code)) {

			JSONObject charger = omsResultObject.getJSONObject("pojo");

			// 封装字段
			ChargerDetailVo chargerDetailVo = JsonUtils.JsonToObjectOfClass(charger, ChargerDetailVo.class);

			//设备类型
			JSONObject deviceTypeJson = charger.getJSONObject("deviceType");
			if(deviceTypeJson!=null){
				DeviceTypeInfoVo deviceTypeVo = JsonUtils.JsonToObjectOfClass(deviceTypeJson, DeviceTypeInfoVo.class);
				chargerDetailVo.setDeviceType(deviceTypeVo);
			}
			
			// 获取桩的枪头列表
			String plugNoResultJsonString = omsService.getChargerPortsByChargerId(chargerDetailVo.getChargerId())
					.toString();

			LOG.info("获取 【" + chargerDetailVo.getChargerId() + "】 桩充电插头列表接口,OMS返回详细:" + plugNoResultJsonString);

			// json转换
			JSONObject plugNoResultObject = JSONObject.parseObject(plugNoResultJsonString);

			// 插头列表
			List<PlugNoDetailVo> detailVos = new ArrayList<>();
			// 获取操作结果
			String plugNocode = omsResultObject.getString(Constants.OmsServerResultField.CODE);

			if (OmsCode.SUCCESS.equals(plugNocode)) {

				JSONArray plugNoJsonArray = plugNoResultObject.getJSONArray("list");

				for (int j = 0; j < plugNoJsonArray.size(); j++) {

					JSONObject plugNoJson = plugNoJsonArray.getJSONObject(j);

					// 插头编号
					String portNo = plugNoJson.getString("port_no");
					// 插头状态
					Integer chargeStatus = plugNoJson.getInteger("charge_status");
					String userCard = plugNoJson.getString("user_pay_card");

					// 插头详细
					PlugNoDetailVo plugNoDetailVo = new PlugNoDetailVo();
					// 如果卡号不为空
					if (chargeStatus!=0) {

						// 正在使用的用户ID
						if(userCard==null||userCard.equals("")){
							LOG.error("获取用户卡号为空");
							resultJsonObject.put("code", 0);
							resultJsonObject.put("msg", "扫描桩失败");
							return resultJsonObject;
						}
						String userId = userInfoService.getUserIdByUserCard(userCard);

//						if (userId!=null&&userId.length() < 20) {
//							LOG.error("获取插头列表通过主服务器获取用户ID发生错误,卡号为【" + userCard + "】,错误码为 【" + userId + "】");
//							resultJsonObject.put("code", 0);
//							resultJsonObject.put("msg", "扫描桩失败");
//							return resultJsonObject;
//						}
						LOG.info("通过主服务器查询【 " + userCard + "】 卡的userId成功,ID为 【" + userId + "】");
						UserInfo userInfo = userInfoDao.findUserByUserId(userId);
						if(userInfo==null){
							LOG.error("用户userid【" + userId + "】有无");
							resultJsonObject.put("code", 0);
							resultJsonObject.put("msg", "扫描桩失败");
							return resultJsonObject;
						}
						// 正在使用的用户用到的基本信息
						UserDetailVo userDetailVo = new UserDetailVo();
						userDetailVo.setNickName(userInfo.getNickname());
						userDetailVo.setPhone(userInfo.getTelephone());
						userDetailVo.setUserId(userInfo.getUser_id());

						// 设置正在使用的用户
						plugNoDetailVo.setUseUser(userDetailVo);
					}

					plugNoDetailVo.setPortNo(portNo);
					plugNoDetailVo.setChargeStatus(chargeStatus.toString());

					// 将插头信息加入插头列表中
					detailVos.add(plugNoDetailVo);
				}
			}
			// 设置桩插头列表
			chargerDetailVo.setPlugNoList(detailVos);

			resultJsonObject.put("chargerDetailVo", chargerDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			Response response = CodeUtils.getCodeByOMSServerCode(code);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}
	

	@Override
	public JSONObject getChargerPlugStatus(String chargerId, String plugNo) throws AvroRemoteException {

		JSONObject resultJsonObject = null;

		String resultJsonString = omsService.getChargerPortStatus(chargerId, plugNo).toString();

		LOG.info("OMS 获取【" + chargerId + "】 电桩第 【" + plugNo + "】 插头状态返回结果: " + resultJsonString);
		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		// 获取操作结果
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);

		// 操作成功
		if (OmsCode.SUCCESS.equals(code)) {
			
			JSONObject plugNoJson = omsResultObject.getJSONObject("pojo");
			resultJsonObject = JsonUtils.getSuccessJson();
			
			// 封装字段
			PlugNoDetailVo plugNoDetailVo = JsonUtils.JsonToObjectOfClass(plugNoJson, PlugNoDetailVo.class);
			resultJsonObject.put("plugNoDetailVo", plugNoDetailVo);
		} else {
			Response response = CodeUtils.getCodeByOMSServerCode(code);
			resultJsonObject = JsonUtils.getFailJson(response);
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject getUsingChargerByUserId(String userCard) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();

		String resultJsonString = omsService.getCurrentUseBookOrChargeNumbers(userCard).toString();

		LOG.info("OMS获取 【" + userCard + "】 卡号正在使用桩返回详细:" + resultJsonString);

		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		// 获取操作结果
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);

		// 操作成功
		if (OmsCode.SUCCESS.equals(code)) {

			JSONObject usingJsonObject = omsResultObject.getJSONObject("pojo");
			// 封装字段
			UsingNum usingNum = JsonUtils.JsonToObjectOfClass(usingJsonObject, UsingNum.class);

			// 重新命名预约个数
			String reservationNo = usingJsonObject.getString("bespeak_no");
			usingNum.setReservationNo(reservationNo);

			resultJsonObject.put("usingNum", usingNum);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			Response response = CodeUtils.getCodeByOMSServerCode(code);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject getPlugsListByChargerId(String chargerId) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();

		String resultJsonString = omsService.getChargerPortsByChargerId(chargerId).toString();

		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);

		// 获取操作结果
		String code = omsResultObject.getString(Constants.OmsServerResultField.CODE);

		LOG.info("获取 【" + chargerId + "】 桩充电插头列表接口,OMS返回代码:" + code);

		// 操作成功
		if (OmsCode.SUCCESS.equals(code)) {

			// 插头列表
			List<PlugNoDetailVo> detailVos = new ArrayList<>();
			// 获取操作结果
			String plugNocode = omsResultObject.getString(Constants.OmsServerResultField.CODE);

			// 获取插头成功
			if (OmsCode.SUCCESS.equals(plugNocode)) {

				// 得到插头列表
				JSONArray plugNoJsonArray = omsResultObject.getJSONArray("list");

				// 遍历解析
				for (int j = 0; j < plugNoJsonArray.size(); j++) {

					JSONObject plugNoJson = plugNoJsonArray.getJSONObject(j);

					String portNo = plugNoJson.getString("port_no");
					String chargeStatus = plugNoJson.getString("charge_status");
					String userCard = plugNoJson.getString("user_pay_card");

					// 插头详细
					PlugNoDetailVo plugNoDetailVo = new PlugNoDetailVo();
					plugNoDetailVo.setPortNo(portNo);
					plugNoDetailVo.setChargeStatus(chargeStatus);

					// 如果卡号不为空
					if (userCard != null && !"".equals(userCard)) {

						String userId = userInfoService.getUserIdByUserCard(userCard);

//						if (userId.length() < 20) {
//							LOG.error("获取插头列表通过主服务器获取用户ID发生错误,卡号为【" + userCard + "】,错误码为 【" + userId + "】");
//						}
						LOG.info("通过主服务器查询【 " + userCard + "】 卡的userId成功,ID为 【" + userId + "】");
						
						UserInfo userInfo = userInfoDao.findUserByUserId(userId);

						// 正在使用的用户信息
						UserDetailVo userDetailVo = new UserDetailVo();
						userDetailVo.setNickName(userInfo.getNickname());
						userDetailVo.setPhone(userInfo.getTelephone());
						userDetailVo.setUserId(userInfo.getUser_id());

						// 设置正在使用的用户
						plugNoDetailVo.setUseUser(userDetailVo);
					}
					// 加入列表中
					detailVos.add(plugNoDetailVo);
				}
			}

			resultJsonObject.put("plugNoDetailVo", detailVos);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			Response response = CodeUtils.getCodeByOMSServerCode(code);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public ResultMappingEntity getRate(String chargerId) throws AvroRemoteException {
		
		ResultMappingEntity resultMappingEntity = null;

		String resultJsonString = omsService.getChargerRate(chargerId).toString();

		LOG.info("获取【" + chargerId + "】 此电桩的费率,OMS返回详细:" + resultJsonString);
		// json转换
		JSONObject omsResultObject = JSONObject.parseObject(resultJsonString);
		JSONArray rateList = omsResultObject.getJSONArray("list");
		List<RateVo> rateVos = new ArrayList<>();
			
		for (int i = 0; i < rateList.size(); i++) {
			JSONObject rateObject = rateList.getJSONObject(i);
			RateVo rateVo = JsonUtils.JsonToObjectOfClass(rateObject, RateVo.class);
			rateVos.add(rateVo);
		}
		resultMappingEntity = Result.responseBody(Response.SUCCESS.getCode(), Response.SUCCESS.getMsg(), rateVos);
		
		return resultMappingEntity;
	}
}










